layui.use(['layer', 'form', 'element', 'util'], function () {
    const [layer, form, element, util] = layui.$modules = [layui.layer, layui.form, layui.element, layui.util];
    let progressTimer = null;
    const MAX_KEYWORD_LENGTH = 128;

    //================ 工具函数 ================//
    const utils = {
        formatSize: bytes => {
            if (+bytes === 0) return '0 B';
            const units = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(1024));
            return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${units[i]}`;
        },

        escapeRegex: str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),

        highlight: (content, keyword, isRegex) => {
            try {
                const pattern = isRegex ? keyword : utils.escapeRegex(keyword);
                return content.replace(new RegExp(pattern, 'g'), '<mark class="highlight">$&</mark>');
            } catch (e) {
                console.error("Regex error:", e);
                return content;
            }
        },

        showLoading: () => layer.load(30, {shade: [0.3, '#fff']}),

        handleError: (error, defaultMsg) => {
            console.error(error);
            layer.msg(error.responseJSON?.msg || error.statusText || defaultMsg);
        },

        copyToClipboard: text => {
            if (!text || text.trim() === '') {
                layer.msg('没有可复制的日志内容', {icon: 2});
                return;
            }
            // 使用现代剪贴板API
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(text).then(() => {
                    layer.msg('日志内容已复制到剪贴板', {icon: 1});
                }).catch(err => {
                    console.error('复制失败:', err);
                    layer.msg('复制失败，请手动选择内容复制', {icon: 2});
                });
            } else {
                // 兼容旧版浏览器
                const textarea = document.createElement('textarea');
                textarea.value = text;
                textarea.style.position = 'fixed';  // 防止滚动
                document.body.appendChild(textarea);
                textarea.select();
                try {
                    const successful = document.execCommand('copy');
                    if (successful) {
                        layer.msg('日志内容已复制到剪贴板', {icon: 1});
                    } else {
                        layer.msg('复制失败，请手动选择内容复制', {icon: 2});
                    }
                } catch (err) {
                    console.error('复制失败:', err);
                    layer.msg('复制失败，请手动选择内容复制', {icon: 2});
                } finally {
                    document.body.removeChild(textarea);
                }
            }
        }
    };

    //================ 核心功能模块 ================//
    const core = {
        // 日志根目录
        rootPaths: [],
        // 文件列表
        currentFile: null,
        // 日志根目录配置
        defaultConfig: JSON.parse(localStorage.getItem("defaultLogRoot") || '{}'),
        // 自动调用接口
        autoSearchEnabled: localStorage.getItem('autoSearchEnabled') === 'true',
        // 新增最大连续调用次数配置
        maxAutoCalls: parseInt(localStorage.getItem('maxAutoCalls') || 5),
        // 是否启用详细模式(换行日志、堆栈日志)
        whetherVerboseModeIsEnabled: localStorage.getItem('whetherVerboseModeIsEnabled') === 'true',
        // 手动操作时重置计数器
        autoCallCount: 0,

        init: function () {
            this.bindEvents();
            this.loadFiles();
            form.render();
        },

        bindEvents: function () {
            // 修复事件绑定方式
            $('#refreshFileList').on('click', () => this.loadFiles());
            $('#clearBtn').on('click', () => this.clearSearch());
            $('#searchBtn').on('click', () => this.search());
            $('#keyword').on('keydown', e => {
                if (e.which === 13) this.search();
                return true; // 允许默认输入行为
            });
            // 修改设置按钮点击事件
            $('#setUp').on('click', () => this.showSetupDialog());
            $('#saveConfigBtn').on('click', () => this.saveConfigBtn());

            // 修复文件点击事件
            $('#logFileList').on('click', '.file-item', function () {
                $('.file-item').removeClass('active');
                $(this).addClass('active');
                core.currentFile = $(this).data('path');
                $('#currentFile').val(core.currentFile);
                $('#keyword').focus(); // 自动聚焦到搜索框
            });

            // 修复表单初始化 - 匹配模式
            form.on('select(matchMode)', ({value}) => {
                const tooltipContent = value === 'true' ?
                    '正则匹配模式：支持复杂表达式' :
                    '普通匹配模式：简单关键词匹配';

                // 先移除可能存在的提示框
                $('.layui-layer-tips').remove();

                // 确定提示框的目标元素
                let tipTarget = $('#matchMode').next('.layui-form-select').find('div.layui-select-title');

                layer.tips(tooltipContent, tipTarget, {
                    tips: [4, '#000000'],
                    time: 4000,
                    skin: 'matchmode-tip',
                    success: function (layero, index) {
                        $(layero).addClass('matchmode-tip');
                    }
                });
            });
            // 修复表单初始化 - 自动切换文件
            form.on('select(enableLoopSearch)', ({value}) => {
                const tooltipContent = value === 'true' ?
                    '开启：当前文件未查询到自动切换下一个文件' :
                    '关闭：当前文件未查询到需手动切换下一个文件';

                // 先移除可能存在的提示框
                $('.layui-layer-tips').remove();

                // 确定提示框的目标元素
                let tipTarget = $('#enableLoopSearch').next('.layui-form-select').find('div.layui-select-title');

                layer.tips(tooltipContent, tipTarget, {
                    tips: [4, '#000000'],
                    time: 4000,
                    skin: 'matchmode-tip',
                    success: function (layero, index) {
                        $(layero).addClass('matchmode-tip');
                    }
                });
            });

            // 新增一键复制开关事件监听
            form.on('select(toggleCopyBtns)', ({value}) => {
                const tooltipContent = value === 'true' ?
                    '开启：在每行日志附近显示一键复制按钮' :
                    '关闭：无';

                // 先移除可能存在的提示框
                $('.layui-layer-tips').remove();

                // 确定提示框的目标元素
                let tipTarget = $('#toggleCopyBtns').next('.layui-form-select').find('div.layui-select-title');

                layer.tips(tooltipContent, tipTarget, {
                    tips: [4, '#000000'],
                    time: 4000,
                    skin: 'matchmode-tip',
                    success: function (layero, index) {
                        $(layero).addClass('matchmode-tip');
                    }
                });
            });


            // 初始化输入框状态
            $('#keyword')
                .prop('disabled', false)
                .removeAttr('readonly')
                .focus();

            // 新增复制日志按钮点击事件
            $('#copyLogBtn').on('click', () => {
                // 克隆logContent元素，移除复制按钮，再获取文本
                const $logContent = $('#logContent').clone();
                $logContent.find('.copy-log-btn').remove();
                const text = $logContent.text().trim();
                if (text) {
                    utils.copyToClipboard(text);
                } else {
                    layer.msg('没有可复制的日志内容', {icon: 2});
                }
            });
        },

        loadFiles: async function () {
            const loading = utils.showLoading();
            try {
                const res = await $.ajax({
                    url: '/sys/weblog/check-resource',
                    method: 'GET',
                    data: {
                        resourcePath: this.defaultConfig.resourcePath,
                        queryFileName: $('#queryFileName').val()
                    }
                });

                if (res.code === 0) {
                    this.renderFileList(res.data);
                    $('#currentRootDir').text(this.defaultConfig.description || res.extendProps.resourcePathDefault.description);
                }

                $('#currentRootDir').text(
                    this.defaultConfig.description ||
                    res.extendProps?.resourcePathDefault?.description ||
                    '未设置根目录'
                );
            } catch (error) {
                utils.handleError(error, '加载文件列表失败');
            } finally {
                layer.close(loading);
            }


        },

        renderFileList: function (files) {
            core.rootPaths = files;
            const html = files.map(file => `
            <!-- 边框 -->
            <div class="file-item"  data-path="${file.filePath}"  data-size="${file.fileSize}"   style="font-size:18px;  border: 1px solid #ccc; padding: 8px; border-radius: 4px; margin-bottom: 4px;">     
                <i class="layui-icon ${file.filePath === this.currentFile ? 'layui-icon-file' : 'layui-icon-file'}"></i>
                    ${file.fileName}
                <!-- 虚线 -->
                <span  class="file-size" style="font-size:15px; border-top: 1px dashed #ccc; display: inline-block; width: 100%; margin: 4px 0;">
                  <!--  文件大小 -->
                  ${utils.formatSize(file.fileSize)}
                </span>
            </div>
            `).join('');
            $('#logFileList').html(html);
        },

        search: async function (isAuto = false) { // 新增参数区分自动/手动调用
            if (!this.validateSearch()) return;

            const params = {
                lookFilePath: this.currentFile,
                logContent: $('#keyword').val().trim(),
                whetherToEnableRegex: $('#matchMode').val() === 'true',
                whetherVerboseModeIsEnabled: core.whetherVerboseModeIsEnabled
            };

            const loading = utils.showLoading();
            this.showProgress();

            try {
                const res = await $.ajax({
                    url: '/sys/weblog/queryLogs',
                    method: 'GET',
                    data: params
                });
                if (res.code === 0) {
                    this.renderResults(res.data, params);
                    // 手动操作时重置计数器
                    if (!isAuto) core.autoCallCount = 0;
                } else {
                    const autoSwitchEnabled = $('#enableLoopSearch').val() === 'true';
                    if (res.msg !== '未找到匹配内容' || !autoSwitchEnabled) {
                        utils.handleError(res, res.msg);
                        return;
                    }
                    if (res.msg === '未找到匹配内容') {
                        // 仅在自动调用时检查次数限制
                        if (isAuto) {
                            if (core.autoCallCount >= core.maxAutoCalls) {
                                layer.msg(`已达到最大连续调用次数(${core.maxAutoCalls})限制，请手动点击查询`, {icon: 2});
                                core.autoCallCount = 0;
                                return;
                            }
                            core.autoCallCount++;
                        }

                        const currentIndex = core.rootPaths.findIndex(
                            file => file.filePath === this.currentFile
                        );

                        if (currentIndex === -1) return;

                        const nextFile = core.rootPaths[currentIndex + 1];

                        if (nextFile && autoSwitchEnabled) {
                            const $nextItem = $(`.file-item[data-path="${nextFile.filePath}"]`);
                            if ($nextItem.length) {
                                $nextItem.click();
                                $nextItem.get(0).scrollIntoView({behavior: 'smooth', block: 'center'});
                                if (core.autoSearchEnabled) {
                                    setTimeout(() => this.search(true), 0);
                                } else {
                                    layer.msg('未找到匹配内容，已切换到下一个文件，请手动点击查询', {icon: 2});
                                }
                            }
                        } else {
                            core.autoCallCount = 0;
                            layer.msg('未找到匹配内容，已是最后一个文件', {icon: 2});
                        }
                    }
                }
            } catch (error) {
                utils.handleError(error, '搜索失败');
            } finally {
                this.hideProgress();
                layer.close(loading);
            }
        },

        renderResults: function (content, {logContent, whetherToEnableRegex}) {
            const highlighted = utils.highlight(content || '无匹配内容', logContent, whetherToEnableRegex);
            const matchCount = (content.match(new RegExp(whetherToEnableRegex ?
                logContent : utils.escapeRegex(logContent), 'g')) || []).length;

            // 根据开关状态决定是否渲染复制按钮
            const isCopyBtnsEnabled = $('#toggleCopyBtns').val() === 'true';
            const lines = highlighted.split('\r\n\r\n').map(line => {
                return isCopyBtnsEnabled
                    ? `<div class="log-line">${line}<button class="layui-btn layui-btn-sm copy-log-btn" style="margin-left: 10px;"><i class="layui-icon layui-icon-copy"></i> 一键复制</button></div>`
                    : `<div class="log-line">${line}</div>`;
            }).join('');

            // 使用原生DOM方法代替jQuery的.html()方法
            const logContentElement = document.getElementById('logContent');
            logContentElement.innerHTML = lines;

            $('#matchCount').text(`匹配数：${matchCount}`);
            $('#searchStatus').text('搜索完成');

            // 如果开关开启，绑定复制按钮事件
            if (isCopyBtnsEnabled) {
                const copyButtons = logContentElement.getElementsByClassName('copy-log-btn');
                Array.from(copyButtons).forEach(button => {
                    button.removeEventListener('click', this.copyLogHandler);
                    button.addEventListener('click', this.copyLogHandler);
                });
            }
        },

        // 新增复制日志处理函数
        copyLogHandler: function () {
            const logLine = this.parentElement.cloneNode(true);
            logLine.querySelector('button').remove();
            utils.copyToClipboard(logLine.textContent);
        },

        showSetupDialog: function () {
            layer.prompt({
                title: '管理员验证',
                formType: 1,
                success: function (layero, index) {
                    $(layero).find('.layui-layer-btn0').css({
                        'background-color': '#00997a',
                        'color': 'white'
                    });
                }
            }, (password, index) => {
                this.loadRootPaths(password, index);
            });
        },

        saveConfigBtn: function () {
            const resourcePath = $('#rootPathSelect').val();
            if (resourcePath) {
                // 从缓存中查找对应路径配置
                const selectedPath = this.rootPaths.find(p => p.resourcePath === resourcePath);

                if (selectedPath) {
                    // 构建完整配置对象
                    const config = {
                        resourcePath: selectedPath.resourcePath,
                        description: selectedPath.description
                    };

                    // 存储到localStorage
                    localStorage.setItem('defaultLogRoot', JSON.stringify(config));

                    // 更新显示
                    $('#currentRootDir').text(config.description);
                    layer.msg('配置保存成功', {icon: 1});

                    // 隐藏设置弹框
                    $('#setUpModal').hide();

                    // 新增自动调用接口配置保存
                    const autoSearchEnabled = $('#enableAutoSearch').val() === 'true';
                    core.autoSearchEnabled = autoSearchEnabled;
                    localStorage.setItem('autoSearchEnabled', autoSearchEnabled);

                    // 新增是否启用详细模式(换行日志、堆栈日志)配置保存
                    const whetherVerboseModeIsEnabled = $('#whetherVerboseModeIsEnabled').val() === 'true';
                    core.whetherVerboseModeIsEnabled = whetherVerboseModeIsEnabled;
                    localStorage.setItem('whetherVerboseModeIsEnabled', whetherVerboseModeIsEnabled);

                    // 刷新文件列表
                    this.defaultConfig = config;
                    this.loadFiles();
                }
            } else {
                layer.msg('请选择一个日志根目录', {icon: 5});
            }
        },

        loadRootPaths: async function (password, index) {
            try {
                const res = await $.get('/sys/weblog/queryRootPathAccessibleLogs', {passWord: password});
                if (res.code === 0) {
                    this.renderSetupDialog(res, index);
                } else {
                    utils.handleError(res, res.msg);
                }
            } catch (error) {
                utils.handleError(error, '加载配置失败');
            }
        },


        renderSetupDialog: function (res, index) {
            this.rootPaths = res.data;

            layer.open({
                type: 1,
                title: '<i class="layui-icon layui-icon-set"></i> 系统设置',
                area: ['620px', '300px'],
                shade: 0.4,
                content: $('#setUpTpl').html(),
                success: (layero, index) => {
                    // 初始化表单
                    this.initSetupForm(res);
                    form.render();

                    // 绑定取消按钮
                    $('#cancelConfigBtn').click(() => layer.close(index));

                    // 绑定保存按钮
                    $('#saveConfigBtn').off('click').click(() => this.saveConfig());
                }
            });
            layer.close(index);
        },


        initSetupForm: function (res) {
            // 生成根目录选项
            let html = '<option value="">请选择日志根目录</option>';
            res.data.forEach(p => {
                html += `<option value="${p.resourcePath}">${p.description}</option>`;
            });
            $('#rootPathSelect').html(html);

            // 设置默认值
            const defaultConfig = JSON.parse(localStorage.getItem('defaultLogRoot') || '{}');
            if (defaultConfig.resourcePath) {
                $('#rootPathSelect').val(defaultConfig.resourcePath);
            }

            // 设置自动搜索开关
            const autoSearchEnabled = localStorage.getItem('autoSearchEnabled') === 'true';
            $('#enableAutoSearch').val(autoSearchEnabled.toString());

            // 设置是否启用详细模式(换行日志、堆栈日志)开关
            const whetherVerboseModeIsEnabled = localStorage.getItem('whetherVerboseModeIsEnabled') === 'true';
            $('#whetherVerboseModeIsEnabled').val(whetherVerboseModeIsEnabled.toString());

            // 新增最大调用次数回显
            const storedMaxAutoCalls = localStorage.getItem('maxAutoCalls');
            const maxAutoCallsValue = storedMaxAutoCalls ? parseInt(storedMaxAutoCalls) : core.maxAutoCalls;
            $('#maxAutoCalls').val(maxAutoCallsValue);
        },


        saveConfig: function () {
            const resourcePath = $('#rootPathSelect').val();
            if (!resourcePath) {
                layer.msg('请选择日志根目录', {icon: 5});
                return;
            }

            // 保存根目录配置
            const selectedPath = this.rootPaths.find(p => p.resourcePath === resourcePath);
            if (selectedPath) {
                const config = {
                    resourcePath: selectedPath.resourcePath,
                    description: selectedPath.description
                };
                localStorage.setItem('defaultLogRoot', JSON.stringify(config));
                this.defaultConfig = config;
                $('#currentRootDir').text(config.description);
            }

            // 保存自动搜索配置
            const autoSearchEnabled = $('#enableAutoSearch').val() === 'true';
            localStorage.setItem('autoSearchEnabled', autoSearchEnabled);
            this.autoSearchEnabled = autoSearchEnabled;

            // 新增保存最大调用次数配置
            const maxAutoCalls = $('#maxAutoCalls').val();
            if (!isNaN(maxAutoCalls)) {
                core.maxAutoCalls = parseInt(maxAutoCalls);
                localStorage.setItem('maxAutoCalls', core.maxAutoCalls);
            }

            // 保存是否启用详细模式(换行日志、堆栈日志)配置
            const whetherVerboseModeIsEnabled = $('#whetherVerboseModeIsEnabled').val() === 'true';
            localStorage.setItem('whetherVerboseModeIsEnabled', whetherVerboseModeIsEnabled);
            this.whetherVerboseModeIsEnabled = whetherVerboseModeIsEnabled;

            layer.msg('配置保存成功', {icon: 1});
            layer.closeAll();
            this.loadFiles();
        },

        validateSearch: function () {
            const errors = [];
            if (!this.currentFile) errors.push('请选择日志文件');

            const keyword = $('#keyword').val().trim();
            if (!keyword) errors.push('请输入搜索关键词');
            if (keyword.length > MAX_KEYWORD_LENGTH) errors.push('关键词过长');
            if (keyword.length < 3) errors.push('关键词至少3个字符');

            // const isRegex = $('#matchMode').val() === 'true';
            // if (!isRegex && /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(keyword)) {
            //     errors.push('普通模式不支持特殊字符');
            // }

            if (errors.length) {
                layer.msg(errors.join('，'));
                return false;
            }
            return true;
        },

        clearSearch: function () {
            $('#keyword').val('');
            $('#logContent').html('<div class="log-placeholder"><i class="layui-icon layui-icon-template-1"></i><p>请选择日志文件并输入关键词进行查询</p></div>');
            $('#searchStatus').text('准备就绪');
            $('#matchCount').text('');
            $('.file-item').removeClass('active');
            this.currentFile = null;
        },

        showProgress: function () {
            clearInterval(progressTimer);
            $('#searchProgress').show();

            // 禁用过渡并立即重置到0%
            $('#searchProgress .layui-progress-bar').css('transition', 'none').css('width', '0%');

            // 下一帧恢复过渡
            requestAnimationFrame(() => {
                $('#searchProgress .layui-progress-bar').css('transition', '');
                let progress = 0;
                progressTimer = setInterval(() => {
                    progress = Math.min(0, progress + 2);
                    element.progress('searchProgress', `${progress}%`);
                }, 300);
            });
        },

        hideProgress: function () {
            clearInterval(progressTimer);
            progressTimer = null;

            // 禁用过渡并立即设置最终进度
            $('#searchProgress .layui-progress-bar').css('transition', 'none').css('width', '100%');

            // 下一帧恢复过渡
            requestAnimationFrame(() => {
                element.progress('searchProgress', '100%');
                $('#searchProgress').show();

                setTimeout(() => {
                    $('#searchProgress').hide();
                }, 800);
            });
        }
    };

    //================ 初始化 ================//
    $(function () {
        // 全局AJAX配置
        $.ajaxSetup({
            beforeSend: xhr => {
                const token = localStorage.getItem("log_token");
                if (token) xhr.setRequestHeader("token", token);
            },
            complete: xhr => {
                if ([401, 403].includes(xhr.status)) {
                    localStorage.removeItem("log_token");
                    layer.msg("会话已过期，请重新登录", {icon: 5});
                    setTimeout(() => location.href = "/login", 1500);
                }
            }
        });

        // 启动核心模块时加载配置
        core.loopSearchEnabled = $('#enableLoopSearch').val() === 'true';
        core.init();

        // 额外初始化输入框
        form.render('input');
        $('#keyword').focus();

        // 新增加载最大调用次数配置
        core.maxAutoCalls = parseInt(localStorage.getItem('maxAutoCalls') || 5);
    });

    // 新增循环查找开关事件监听
    form.on('select(enableLoopSearch)', ({value}) => {
        core.loopSearchEnabled = value === 'true';


    });

});
